<template>
  <view>
    <u-sticky offset-top="10">
      <view class="head-wrapper">
        <image src="https://www.douluodalu.icu:9000/school/static/head_topic.png" @click="toTopic" class="head-topic"></image>
        <u-tabs
            :current="tagIndex"
            @click="toScroll"
            :list="list4"
            lineWidth="20"
            lineHeight="7"
            :lineColor="`url(${lineBg}) 100% 100%`"
            :activeStyle="{
        color: '#303133',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
    }"
            :inactiveStyle="{
        color: '#606266',
        transform: 'scale(1)'
    }"
            itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;"
        >
        </u-tabs>
        <image src="https://www.douluodalu.icu:9000/school/static/search.png" @click="toSearch" class="search"></image>


      </view>
    </u-sticky>
    <u-sticky>
      <view style="display: flex;justify-content: center">
        <view v-show="showRefreshText" class="refresh" style="">为你选出{{ RefreshPostNum }}条好贴</view>
      </view>
    </u-sticky>

    <IndexSkeleton v-show="showSkeleton"/>
    <view class="content">
      <image @click="onRefresh" class="refresh-image" style="" src="http://www.douluodalu.icu:9000/school/static/refresh.png"></image>
      <swiper :current="tagIndex" class="swiper"
              :circular="false" @change="swiperChange"
              swiperDuration="200">

        <!--      关注-->
        <swiper-item>
          <scroll-view scroll-y style="height: 100vh;padding-top: 20px">
            <Blog v-if="postListMap[tagIndex]?.records?.length > 0" v-for="(item, index) in postListMap[tagIndex].records" :key="item?.id" :post="item"/>
            <u-empty v-else
                text="你关注的用户还没有发布过内容哦"
                mode="list"
                icon="https://cdn.uviewui.com/uview/empty/list.png">
            </u-empty>
            <view style="height:100px"></view>
          </scroll-view>
        </swiper-item>
        <!--      推荐-->
        <swiper-item>
          <scroll-view scroll-y style="height: 100vh;padding-top: 20px"
                       @scrolltolower="onScrollToLower()"
                       :scroll-top="scrollTop"
                       :refresher-enabled="true"
                       :refresher-triggered="trigger"
                       :refresher-threshold="100"
                       @refresherrefresh="onRefresh">
            <Blog  @longtap="handleRemove(item,index)"
                   v-for="(item, index) in postListMap[tagIndex].records"
                  :key="item?.id" :post="item"/>
            <view style="height:100px"></view>
          </scroll-view>
        </swiper-item>
        <!--      视频-->
<!--        最新-->
              <swiper-item>
                <scroll-view scroll-y style="height: 100vh">
                  <Blog  @longtap="handleRemove(item,index)" v-for="(item, index) in postListMap[tagIndex].records" :key="item.id" :post="item"/>
                  <view style="height:100px"></view>

                </scroll-view>
              </swiper-item>
        <!--      图文-->
<!--        <swiper-item>-->
<!--          <scroll-view scroll-y style="height: 100vh;padding-top: 20px">-->
<!--            <Blog  v-for="(item, index) in postListMap[tagIndex]?.records" :key="item?.id" :post="item"/>-->


<!--            <view style="height:100px"></view>-->

<!--          </scroll-view>-->
<!--        </swiper-item>-->
      </swiper>
    </view>
  </view>
  <u-action-sheet cancelText="取消" @close="closeRemoveAction"
                  @select="selectClick"
                  :closeOnClickOverlay="true"
                  :actions="removeActionList"
                  :round="10"
                  :show="showRemove"></u-action-sheet>
  <tabbar></tabbar>

</template>

<script>
import Blog from "@/components/Blog.vue";
import tabbar from "@/components/tabbar/tabbar.vue";
import {listArticle, removePostById} from "@/api/article";
import IndexSkeleton from "@/components/skeleton/IndexSkeleton.vue";
import {getPostList} from "@/api/post";
import {getToken, getUserId} from "@/utils/auth";

export default {

  components: {IndexSkeleton, Blog, tabbar},
  data() {
    return {
      scrollTop: 0,
      percentage:0,
      publishingPost:{},
      publishing:false,
      old: {
        scrollTop: 0
      },
      showSkeleton: false,
      showRemove: false,
      removeActionList: [{
        name:'删除',
      }],
      tagIndex: 1,
      trigger: false,
      showRefreshText: false,
      RefreshPostNum: 0,
      postList: [],
      loading: false,
      lineBg: "",
      list4: [
        {name: '关注'},
        {name: '推荐', badge: {isDot: true}},
        {name: '最新',},
        // {name: '图文',}
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        authorName: null,
        channelId: null,
        labels: null,
        countyId: null,
        createdTime: null,
        publishTime: null,
        origin: null,
      },
      finish: false,
      postList0: [],
      postList1: [],
      postList2: [],
      // postList3: [],
      removeItem:{},
      postListMap: [
        [],
        [],
        [],
        []
      ],
      articleDtoMap: [
        {
          isFollowed: true,
          isRecommend: false,
          isVideo: false,
          isImage: false,
          currentPage: 1,
          pageSize: 15
        },
        {
          isFollowed: false,
          isRecommend: true,
          isVideo: false,
          isImage: false,
          currentPage: 1,
          pageSize: 15
        },
        {
          isFollowed : false,
          isRecommend: false,
          isVideo: true,
          isImage:false,
          currentPage: 1,
          pageSize: 15
        },
        // {
        //   isFollowed: false,
        //   isRecommend: false,
        //   isVideo: false,
        //   isImage: true,
        //   currentPage: 1,
        //   pageSize: 15
        // }
      ],
      articleDto0: {
        isFollowed: true,
        isRecommend: false,
        isVideo: false,
        isImage: false,
        currentPage: 1,
        pageSize: 15
      },
      articleDto1: {
        isFollowed: false,
        isRecommend: true,
        isVideo: false,
        isImage: false,
        currentPage: 1,
        pageSize: 15
      },
      articleDto2:{
        isFollowed : false,
        isRecommend: false,
        isVideo: true,
        isImage:false,
        currentPage: 1,
        pageSize: 15
      },
      // articleDto3: {
      //   isFollowed: false,
      //   isRecommend: false,
      //   isVideo: false,
      //   isImage: true,
      //   currentPage: 1,
      //   pageSize: 15
      // },
    };
  },
  mounted() {
    // 监听事件
    uni.$on('newPost', (params) => {
      if (params.data != null) {
        uni.pageScrollTo({
          scrollTop: 0, // 设置滚动到顶部的位置
          duration: 300 // 滚动动画时长，单位 ms
        });
        this.scrollTop = this.scrollTop === 0 ? -1 : 0;
        this.postListMap[1].records = [params.data, ...this.postListMap[1]?.records]
        this.tagIndex = 1
      } else {
        this.getList();
      }
      // 处理参数

    });
  },
  unmounted() {
    // 移除监听事件
    uni.$off('newPost');
  },
  onLoad() {
  },
  onUnload() {
  },
  methods: {
    handleRemove(item,index){
      let userId = getUserId();
      if (userId !== null && userId !== '' && userId !== undefined && item.authorId == userId) {
        this.showRemove = true
        this.removeItem.item = item
        this.removeItem.index = index
      }

    },
    selectClick(index){
      if(index?.name === '删除'){
        let _this = this
        uni.showModal({
          title: '提示',
          content: '内容删除后无法找回，是否确认删除？',
          success: async (res) => {
            if (res.confirm) {
              console.log(this.removeItem)
              console.log(_this.removeItem)
              console.log(_this.removeItem.item)
              const res = await removePostById(_this.removeItem.item.id)
              if(res.code == 200){
                uni.showToast({
                  title: '删除成功',
                  icon: 'none'
                })
                _this.postListMap[_this.tagIndex].records.splice(_this.removeItem.index, 1)
                _this.removeItem = {}
              }else{
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              }

              _this.showRemove = false
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      }
    },
    closeRemoveAction(){
      // this.removeItem = {}
      this.showRemove = false
    },
    async onRefresh() {
      this.showSkeleton = true
      this.trigger = true
      let index = this.tagIndex;
      let list = this.postListMap[index]
      let articleDto = this.articleDtoMap[index]
      this.postListMap[index] = []
      this.articleDtoMap[index].currentPage = 1

      const {data: res} = await getPostList(articleDto)
      this.postListMap[index] = res
      this.RefreshPostNum = res?.records?.length
      this.trigger = false
      this.showRefreshText = true
      this.showSkeleton = false
      setTimeout(() => {
        this.showRefreshText = false
      }, 2000)

    },
    async getList() {
      this.showSkeleton = true
      this.loading = true;
      let index = this.tagIndex;
      let list = this.postListMap[index]
      let articleDto = this.articleDtoMap[index]

      const {data: res} = await getPostList(articleDto)
      this.postListMap[index] = res
        setTimeout(() => {
          this.showSkeleton = false
        }, 1500)
    },
    async onScrollToLower() {
      let index = this.tagIndex;
      let list = this.postListMap[index]
      let articleDto = this.articleDtoMap[index]
      if (list && list.records.length < list.total) {
        articleDto.currentPage++
        const {data: res} = await getPostList(articleDto)
        this.postListMap[index].records = this.postListMap[index]?.records.concat(res?.records)
      } else {
        this.finish = true
        return uni.showToast({icon: 'none', title: '到底了~', position: 'bottom'})
      }

    },
    toSearch() {
      uni.navigateTo({url: '/pages/search/search'})
    },
    toTopic() {
      uni.navigateTo({url: '/pages/topic/AllTopic'})
    },
    toScroll(event) {
      this.tagIndex = event.index
      this.getList()
    },
    swiperChange(event) {
      this.tagIndex = event.detail.current
      this.getList()
    },
  },
  created() {
  },
};
</script>

<style>
.head-wrapper {
  background-color: white;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.head-topic {
  padding-top: 5px;
  width: 25px;
  height: 25px;
}

.search {
  padding-top: 5px;
  padding-right: 5px;
  width: 20px;
  height: 20px;
}

.title {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 60rpx;
}

.swiper {
  height: calc(100vh - 120rpx);
}

.wrap_content {
  border-radius: 20rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background: gray;
  height: 100vh;
  color: aqua;
  font-size: 80px;
  margin: 0rpx 40rpx;
}

.refresh {

  width: max-content;
  padding: 2px 1rem;
  font-size: 0.6rem;
  color: white;
  border-bottom-left-radius: 25px;
  border-bottom-right-radius: 25px;
  border-top-left-radius: 25px;
  border-top-right-radius: 25px;
  background-color: #4ea4f9
}

.refresh-image {
  width: 2rem;
  height: 2rem;
  position: absolute;
  right: 0.5rem;
  bottom: 3.5rem;
  z-index: 100;
  background-color: white;
  padding: 0.3rem;
  scale: 0.8;
  border: 1px solid rgba(154, 154, 154, 0.13);
  border-radius: 10px;
}

</style>
